#import "HTTPAssetResponse.h"
#import "HTTPLogging.h"
#import "AssetsLibrary/AssetsLibrary.h"
#import "DataManager.h"

// Log levels : off, error, warn, info, verbose
// Other flags: trace
static const int httpLogLevel = HTTP_LOG_LEVEL_OFF; // | HTTP_LOG_FLAG_TRACE;

@implementation HTTPAssetResponse

- (id)initWithAssetPath:(NSString*)s
{
	if((self = [super init]))
	{
		HTTPLogTrace();
		
		NSLog(@"requested asset name(%@)", s);

		asset = nil;
		offset = 0;
        buffer = nil;
        bufferSize = 0;
        
        // find asset
        NSMutableDictionary* dic = [[DataManager sharedManager] allAssetDic];
        if ( dic != nil )
        {
            asset = [[dic objectForKey:s] retain];
        }
	}
	return self;
}

- (void)dealloc
{
    if (buffer)
		free(buffer);

    [asset release];
    [super dealloc];
}

- (UInt64)contentLength
{
    if ( asset == nil )
        return 0;
    
    return [[asset defaultRepresentation] size];
}

- (UInt64)offset
{
	return offset;
}

- (void)setOffset:(UInt64)offsetParam
{
    offset = offsetParam;
}

- (NSData *)readDataOfLength:(NSUInteger)lengthParameter
{
    if ( asset == nil )
        return nil;
    
    UInt64 bytesLeftInFile = [self contentLength] - offset;	
	NSUInteger bytesToRead = (NSUInteger)MIN(lengthParameter, bytesLeftInFile);

    if (buffer == NULL || bufferSize < bytesToRead)
	{
		bufferSize = bytesToRead;
		buffer = reallocf(buffer, (size_t)bufferSize);
		if (buffer == NULL)
		{
			return nil;
		}
	}
    
    ALAssetRepresentation* ar = [asset defaultRepresentation];
    int readed = [ar getBytes:buffer fromOffset:offset length:bytesToRead error:nil];
    offset += readed;
 
    return [NSData dataWithBytesNoCopy:buffer length:readed freeWhenDone:NO];
}

- (BOOL)isDone
{
    if ( [self contentLength] == offset )        
        return TRUE;
    
    return FALSE;
}

@end